<?php if (!defined('BASEPATH')) exit('No direct script access allowed');


/**
 * @property mixed auth
 * @property mixed user_model
 */
class User extends CI_Controller {

    var $_register = "_register"; // ten cua session register khi dang ki thanh vien
    var $_fgpassword = "fgpassword";

    function __construct(){
        parent::__construct();
        $this->load->helper(array("url","form", 'my_data_helper'));
        $this->load->library(array("form_validation","session","auth"));
        $this->load->database();
        $this->load->model("user_model");

    }

    public function index() {
        $this->login();
    }

    public function login() {
        if($this->auth->is_Login())
        {
            redirect("blog");
            exit();
        }

        $this->form_validation->set_rules("username","Username","required");
        $this->form_validation->set_rules("password","Password","required");

        if($this->form_validation->run()==FALSE)
        {
            $this->load->view("not_logged_in/login",array("error"=>""));
        }
        else
        {
            $u = $this->input->post("username");
            $p = $this->input->post("password");
            $session = $this->user_model->checkLogin($u,$p);

            if($session)
            {
                if(!$this->auth->is_Active($session['userid'])){

                    $data['error'] = 'Please check mail and active your account !<br/><a href="' . base_url() . 'user/resend_mail/'.$session["userid"].'">Resend the email</a>';
                    $this->load->view("not_logged_in/login",$data);
                }
                else
                {
                    $data = array(
                        "username"  => $session['username'],
                        "userid"    => $session['userid'],
                        "level"  => $session['level'],
                    );

                    $this->auth->set_userdata($data);
                    redirect("user");
                }
            }
            else
            {
                $this->load->view("not_logged_in/login",array("error"=>"Username or Password wrong"));
            }
        }
    }

    //---- Logout
    public function logout()
    {
        $this->session->sess_destroy();
        redirect("");
    }

    //--- Dang ki thanh vien
    function register()
    {
        //--- Neu Login thi khong duoc dang ki
        if($this->auth->is_Login()){
            redirect("");
            exit();
        }

        $this->form_validation->set_rules("name","Full name","required|min_length[6]");
        $this->form_validation->set_rules("username","Username","required|max_length[25]|callback_checkUser");
        $this->form_validation->set_rules("password","Password","required|matches[repassword]");
        $this->form_validation->set_rules("email","Email","required|valid_email|callback_checkEmail");
        $this->form_validation->set_rules("address","Address");
        $this->form_validation->set_rules("gender","Gender","required");

        if($this->form_validation->run()==FALSE){

            $this->load->view("not_logged_in/sign_up",array("error"=>""));
        }
        else
        {

            $salt = create_random_string(5);
            $add = array(
                "name" => $this->input->post("name"),
                "username"  => $this->input->post("username"),
                "salt"      => $salt,
                "password"  => md5($this->input->post("password")),
                "email"     => $this->input->post("email"),
                "address"   => $this->input->post("address"),
                "level"     => 2, // mac dinh la memmber khi dang ki thanh vien
                "gender"    => $_POST['gender'],
                "add_date"  => time(),
                "active"    => 0, // chua kich hoat
            );

            //--- Xử lý ảnh : phần này không bắt buộc
            $img = "";
            $flag = TRUE;
            if($_FILES['image']['name'] != NULL){
                $config['upload_path']   = './images/avatar/';
                $config['allowed_types'] = 'gif|jpg|png';
                $config['encrypt_name']  = true; // ma hoa ten file
                $config['remove_spaces'] = true; // xoa khoang trang
                $this->load->library('upload', $config);

                if(!$this->upload->do_upload("image"))
                {
                    $data['error'] = $this->upload->display_errors();
                    $this->load->view("not_logged_in/sign_up",$data);
                    $flag = FALSE;
                }
                else
                {
                    $img = $this->upload->data();
                    $add['image'] = $img['file_name'];
                }
            }

            if($flag==TRUE){
                //--- Gui mail kich hoat neu add thanh cong
                $message = "";
                if($this->user_model->addUser($add)){

                    $userid = mysql_insert_id();
                    $link_active = base_url()."user/active/?userid=".$userid."&key=".md5($salt);
                    $message  = "Please follow this link to active your acount <br/>";
                    $message .= "Link : <a href=".$link_active.">".$link_active."</a><br/>";
                    $message .= "username : ".$add['username']."<br/>";
                    $message .= "password : ".$this->input->post("password");


                    $this->load->library("email");
                    $this->email->from('tmptmp268@gmail.com', 'YourBlog Email System');
                    $this->email->to($add['email']);

                    $this->email->subject('Active your account!');
                    $this->email->message($message);

                    $this->email->send();

                    $this->session->set_userdata(array($this->_register => TRUE));
                    redirect("user/register_complete");
                }
            }
        }

    }
	function resend_mail($id) {
		$user = $this->user_model->getInfo($id);
		$link_active = base_url()."user/active/?userid=".$user['userid']."&key=".md5($user['salt']);
		$message  = "Please follow this link to active your acount <br/>";
		$message .= "Link : <a href=".$link_active.">".$link_active."</a><br/>";
		$message .= "username : ".$user['username']."<br/>";

		$this->load->library("email");
		$this->email->from('tmptmp268@gmail.com', 'YourBlog Email System');
		$this->email->to($user['email']);

		$this->email->subject('Active your account!');
		$this->email->message($message);

		$this->email->send();

		$this->load->view('not_logged_in/report', array('report' => 'Email has been re-send! Please check your email and active your account!.'));
	}
    //--- Đăng kí thành công
    function register_complete(){

        //--- Neu Login thi khong khong bao
        if($this->auth->is_Login()){
            redirect("");
            exit();
        }

        if($this->session->userdata($this->_register)==TRUE){
            $data['report'] = "You has been register completed ! <br/>
                                   Please check your email address to active your account and use system ! <br/>";

            $this->load->view("not_logged_in/report",$data);
        }
        else
        {
            redirect("user/login");
        }
    }

    //---- Quên mật khẩu
    function fg_password(){

        //--- Neu Login thi khong duoc vao trang nay
        if($this->auth->is_Login()){
            redirect("");
            exit();
        }

        $this->form_validation->set_rules("email","Email","required|valid_email|callback_checkEmailForgot");
        $data['error'] = "";

        if($this->form_validation->run()==FALSE){

            $this->load->view("not_logged_in/fg_password",$data);

        }else{

            $email = $this->input->post("email");
            $info = $this->user_model->getInfoByEmail($email);

            $message = "";
            if($info['active']==1){

                // reset password cho user
                $password = create_random_string(5);
                $reset = array(
                    "password" => md5($password),
                );
                $this->user_model->updateUser($reset,$info['userid']);

                //--- Gui mail cho user
                $this->load->library("email");
                $message  = "Please login with :<br/>";
                $message .= "username :".$info['username']."<br/>";
                $message .= "password:".$password;

                $this->email->from( $this->email->smtp_user, 'YourBlog Email System');
                $this->email->to($email);

                $this->email->subject('Resend password!');
                $this->email->message($message);

                $this->email->send();


                $this->session->set_userdata(array($this->_fgpassword => TRUE));
                redirect("user/fg_complete");

            }else{
                $data['error'] = "You hasn't been actived your account, please check your email again !";
            }

            $this->load->view("not_logged_in/fg_password",$data);
        }

    }

    //----- Thong bao da gui email khi quen mat khau
    function fg_complete(){
        if($this->session->userdata($this->_fgpassword) == TRUE){
            $data['report'] = "Your email has been sending !";
            $this->load->view("not_logged_in/report",$data);
            $this->session->unset_userdata($this->_fgpassword);
        }else{
            redirect("user/login");
        }
    }

    //--- Kick hoat tai khoan
    function active(){

        //--- Neu Login thi khong active
        if($this->auth->is_Login()){
            redirect("");
            exit();
        }

        $userid = $_GET['userid'];
        $key = $_GET['key'];
        $data = array();

        if(is_numeric($userid)){

            $check = $this->user_model->checkActive($userid,$key);

            if($check){

                if($check['active']==1)
                {
                    $data['report'] = "Account has been actived, <a href='".base_url()."user/login'>please login</a> !";
                    $this->session->unset_userdata($this->_register);
                }
                else
                {

                    $update = array(
                        "active_date" => time(),
                        "active"      => 1,
                    );
                    $this->user_model->updateUser($update,$userid);
                    $data['report'] = "Account has been actived, <a href='".base_url()."user/login'>please login</a> !";
                }

            }
            else{
                $data['report'] = "Your account not avaliable !";
            }

        }else{

            $data['report'] = "Invalid link active !";
        }

        $this->load->view("not_logged_in/report",$data);
    }


    //--- Kiểm tra user hợp lệ
    function checkUser($username)
    {
        $id = $this->uri->segment(4);
        if($this->user_model->getUser($username,$id)==TRUE){
            return TRUE;
        }
        else{
            $this->form_validation->set_message("checkUser","Your username has been register, please try again");
            return FALSE;
        }
    }

    //---- Kiem tra Email khi đăng kí
    function checkEmail($email)
    {
        $id = $this->uri->segment(4);
        if($this->user_model->checkEmail($email,$id)==TRUE){
            return TRUE;
        }
        else{
            $this->form_validation->set_message("checkEmail","Email has been exit, please try again");
            return FALSE;
        }
    }

    //--- Kiem tra email khi quen mat khau
    function checkEmailForgot($email)
    {
        if($this->user_model->checkEmail($email)==FALSE){ // co ton tai email
            return TRUE;
        }
        else{
            $this->form_validation->set_message("checkEmailForgot","Email is not avaliable , please try again !");
            return FALSE;
        }
    }

} 